<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .a{
            width: 100px;
            height: 100px;
            background-color: #f00;
            position: absolute;

            /* 禁止用户选中 */
            -webkit-user-select:none ;
            
        }
    </style>
    <script>

        var gapX , gapY ;

        window.onload = function() {

            var oDiv = document.querySelector('.a') ;
            

            // 拖拽：鼠标按下盒子，然后移动鼠标

            oDiv.addEventListener('mousedown' , function(e) {
                var e = e || event ;
                // 获取按下的时候鼠标在盒子中的位置
                gapX = e.offsetX ;
                gapY = e.offsetY ;

                // 鼠标移动事件
                document.addEventListener('mousemove' , fn) ;

                // 鼠标抬起
                document.addEventListener('mouseup' , fn2) ;

            })



            // 鼠标移动事件
            function fn(e) {
                var e = e || event ;
                var x = e.x - gapX ;
                var y = e.y - gapY ;
                oDiv.style.cssText = `left:${x}px;top:${y}px` ;
            }

            // 鼠标抬起
            function fn2() {
                document.removeEventListener('mousemove' , fn) ;
                document.removeEventListener('mouseup' , fn2) ;
            }


        }

       

    </script>
</head>
<body>
    <div class="a">111111111111111111</div>
</body>
</html>